<?php
namespace App\Http\Controllers\wx;


use Common\Service\Wxmsg;

class WechatController extends Controller
{
    public function getIndex()
    {
        $this->valid();
    }

    //验证签名..
    public function valid()
    {
        $echoStr = request("echostr", "");
        $signature = request("signature", "");
        $timestamp = request("timestamp", "");
        $nonce = request("nonce", "");
        $token = config('wx.token');
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = sha1(implode($tmpArr));
        if ($tmpStr == $signature) {
            echo $echoStr;
            exit;
        }
    }

    /**
     * 微信请求入口
     */
    public function postIndex()
    {
        $this->responseMsg();
    }

    //响应消息
    private function responseMsg()
    {
        $postStr = file_get_contents("php://input");
        if (!empty($postStr)) {
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

            $RX_TYPE = trim($postObj->MsgType);
            //消息类型分离
            switch ($RX_TYPE) {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                case "image":
                    $result = $this->receiveImage($postObj);
                    break;
                case "location":
                    $result = $this->receiveLocation($postObj);
                    break;
                case "voice":
                    $result = $this->receiveVoice($postObj);
                    break;
                case "video":
                    $result = $this->receiveVideo($postObj);
                    break;
                case "link":
                    $result = $this->receiveLink($postObj);
                    break;
                default:
                    $result = "unknown msg type: " . $RX_TYPE;
                    break;
            }
            echo $result;
        } else {
            echo "";
            exit;
        }
    }

    //接收事件消息
    private function receiveEvent($object)
    {
        $content = "";
        $event = strtolower($object->Event);
        $serverurl = url('/');
        switch ($event) {
            case "subscribe":
                $content = '你好，欢迎关注';
                //关注写入user表，更新初始化userinfo
                $res = DB::table("users")->where("openid", $object->FromUserName)->first();
                if (!empty($res)) {
                    DB::table("users")->where("openid", $object->FromUserName)->update(array("status" => 1, "gz_time" => time()));
                } else {
                    DB::table("users")->insertGetId(array(
                        'openid' => $object->FromUserName,
                        'gz_time' => time(),
                        'status' => 1
                    ));
                }
                break;
            case "unsubscribe":
                //取消关注，更新user状态为3
                DB::table("users")->where("openid", $object->FromUserName)->update(array("status" => 3, "cancel_time" => time()));
                break;
            case "click":
                $keyword = $object->EventKey;
                if ($keyword == "application") {
                    $content = $serverurl . "/img/application.jpg";
                } else {
                    $content = 'click';
                }
                break;
            case "view":
                $content = "跳转链接 " . $object->EventKey;
                break;
            case "scan":
                $content = static::senariosMessage($object->EventKey, 'scan');
                break;
            case "location":
                $data['latitude'] = $object->Latitude;
                $data['FromUserName'] = $object->FromUserName;
                $data['longitude'] = $object->Longitude;
                $data['precision'] = $object->Precision;
                break;
            case "scancode_waitmsg":
                break;
            case "scancode_push":
                $content = "扫码推事件";
                break;
            case "pic_sysphoto":
                $content = "系统拍照";
                break;
            case "pic_weixin":
                $content = "相册发图：数量 " . $object->SendPicsInfo->Count;
                break;
            case "pic_photo_or_album":
                $content = "拍照或者相册：数量 " . $object->SendPicsInfo->Count;
                break;
            case "location_select":
                $content = "发送位置：标签 " . $object->SendLocationInfo->Label;
                break;
            default:
                $content = "receive a new event: " . $object->Event;
                break;
        }
        if (!$content) {
            return $content;
        }

        if (is_array($content)) {
            if (isset($content[0]['PicUrl'])) {
                $result = WxMsg::transmitNews($object, $content);
            } else if (isset($content['MusicUrl'])) {
                $result = WxMsg::transmitMusic($object, $content);
            }
        } else {
            $result = WxMsg::transmitText($object, $content);
        }
        return $result;
    }

    //接收文本消息
    private function receiveText($object)
    {
        $content = 'hello';
        $result = WxMsg::transmitText($object, $content);
        return $result;
    }

    //接收图片消息
    private function receiveImage($object)
    {
        $content = array("MediaId" => $object->MediaId);
        $result = WxMsg::transmitImage($object, $content);
        return $result;
    }

    //接收位置消息
    private function receiveLocation($object)
    {
        $content = "你发送的是位置，经度为：" . $object->Location_Y . "；纬度为：" . $object->Location_X . "；缩放级别为：" . $object->Scale . "；位置为：" . $object->Label;
        $result = WxMsg::transmitText($object, $content);
        return $result;
    }

    //接收语音消息
    private function receiveVoice($object)
    {
        if (isset($object->Recognition) && !empty($object->Recognition)) {
            $content = "你刚才说的是：" . $object->Recognition;
            $result = WxMsg::transmitText($object, $content);
        } else {
            $content = array("MediaId" => $object->MediaId);
            $result = WxMsg::transmitVoice($object, $content);
        }
        return $result;
    }

    //接收视频消息
    private function receiveVideo($object)
    {
        $content = array("MediaId" => $object->MediaId, "ThumbMediaId" => $object->ThumbMediaId, "Title" => "", "Description" => "");
        $result = WxMsg::transmitVideo($object, $content);
        return $result;
    }

    //接收链接消息
    private function receiveLink($object)
    {
        $content = "你发送的是链接，标题为：" . $object->Title . "；内容为：" . $object->Description . "；链接地址为：" . $object->Url;
        $result = WxMsg::transmitText($object, $content);
        return $result;
    }

    //创建自定义菜单
    public function getCreatemenu()
    {
        $wx = new Wechat();
        $access_token = $wx->get_access_token();
        $serverurl = url('/');

        $data = '
        {
          	"button":[
          	{
          	"name":"客户端",
          	"sub_button":[
              	{
            	"name":"我的订单",
            	"type":"view",
            	"url":"' . $serverurl . '/wx/diversion?src=qzdwxyy"
          	    },
              	{
                	"type":"click",
                 	"name":"在线客服",
                 	"key":"custom"
              	}
            	]
          	},
          	{
                "type":"师傅端",
                "name":"个人中心",
                "url":"http://wx.45tnz.com/home/member/center"
            }
          ]
    	}';
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $access_token;
        $return = $wx->curl_post($url, $data);
        dd($return);
    }

    public function getDeletemenu()
    {
        $wx = new Wechat();
        $access_token = $wx->get_access_token();
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=' . $access_token;
        $return = $wx->curl_get($url);
    }

    /**
     * 主动给指定的人推送一个指定的消息模板(文本信息)
     * @param $opneId
     * @param $content
     */
    public function getTplInfo($opneId, $content)
    {
        $wx = new Wechat();
        $access_token = $wx->get_access_token();
        $data = '
            {
                "touser":"' . $opneId . '",
                "msgtype":"text",
                "text":
                {
                    "content":"' . $content . '"
                }
            }
        ';

        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;
        $return = $wx->curl_post($url, $data);
        return $return;
    }

    /**
     * 主动推送图文消息
     * @param $openId
     */
    public function getSuccessPicInfo($openId, $url, $imgPath)
    {
        $wechat = new Wechat();
        $access_token = $wechat->get_access_token();

        //成功推送图文消息
        $data = '{
            "touser":"' . $openId . '",
            "msgtype":"news",
            "news":{
                "articles": [
                 {
                     "title":"这是图文消息",
                     "description":"description",
                     "url":"' . $url . '",
                     "picurl":"' . $imgPath . '"
                 }
                 ]
            }
        }';

        //客服接口，推送外链接图文消息
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;
        $rs = $wechat->curl_post($url, $data);
        return $rs;
    }
}